package com.lan.bezier.view.ui;

import static com.lan.bezier.view.utils.DensityUtil.dip2px;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;

import androidx.annotation.Nullable;

import com.lan.bezier.view.R;
import com.lan.bezier.view.utils.MeasureUtil;


/**
 * @author zhangshaobo
 * @Email 467107354@qq.com
 * @date 2023/10/17 17:50
 */
public class WaveProgressView extends View{
    private Paint mPaint;
    private Paint mPaint_offset;
    private int mWidth;
    private int mHeight;
    private int mWaveHeight;
    private int mWaveDx;
    private int dx;
    //Bitmap bg_bitmap;
    Bitmap icon_bitmap;
    Bitmap icon_bitmap_temp;
    Rect icon_src_rect;
    Rect bg_src_rect;
    RectF bg_dst_rect;
    RectF icon_dst_rect;
    Rect icon_grey_src_rect;
    RectF icon_grey_dst_rect;
    Path wave_path;
    Path wave_path_offset;
    PorterDuffXfermode xfermode;
    private float mProgress=0.5f;

    public WaveProgressView(Context context) {
        this(context, null);
    }

    public WaveProgressView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WaveProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);


        mPaint_offset = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint_offset.setStyle(Paint.Style.STROKE);
        mPaint_offset.setAntiAlias(true);
        mPaint_offset.setDither(true);
        mPaint_offset.setColor(Color.GRAY);
        mPaint_offset.setStrokeWidth(dip2px(context, 1));

        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
        //bg_bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.flower_back, opt);
        //bg_src_rect = new Rect(0, 0, bg_bitmap.getWidth(), bg_bitmap.getHeight());
        icon_bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.img, opt);
        icon_src_rect = new Rect(0, 0, icon_bitmap.getWidth(), icon_bitmap.getHeight());

        wave_path = new Path();
        wave_path_offset = new Path();

        mWaveDx = getResources().getDisplayMetrics().widthPixels;
        xfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
        mWaveDx = dip2px(context, 300);
        //mWaveDx=mWidth;
    }

    int last_src_bottom = 0;
    float last_dst_bottom = 0f;

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mWidth = MeasureUtil.measureView(widthMeasureSpec, icon_bitmap.getWidth());
        mHeight = MeasureUtil.measureView(heightMeasureSpec, icon_bitmap.getHeight());
        mWaveHeight = dip2px(getContext(), 20);
        //mWaveHeight=(int) ((double)mWidth/15);


        bg_dst_rect = new RectF(0, 0, mWidth, mHeight);

        icon_dst_rect = new RectF(0, 0, mWidth, mHeight);

        icon_grey_src_rect = new Rect(icon_src_rect.left, icon_src_rect.top, icon_src_rect.right, icon_src_rect.bottom);
        icon_grey_dst_rect = new RectF(icon_dst_rect.left, icon_dst_rect.top, icon_dst_rect.right, icon_dst_rect.bottom);
        last_src_bottom = icon_grey_src_rect.bottom;
        last_dst_bottom = icon_grey_dst_rect.bottom;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int layerId = canvas.saveLayer(0, 0, mWidth, mHeight, null, Canvas.ALL_SAVE_FLAG);
        //绘制背景图
        //canvas.drawBitmap(bg_bitmap, bg_src_rect, bg_dst_rect, mPaint);
        //绘制水流
        drawPath(canvas, mWaveDx / 8, Color.CYAN);

        canvas.restoreToCount(layerId);
        //绘制icon
        drawIcon(canvas);
        //drawStroke(canvas);

    }

    private void drawIcon(Canvas canvas) {
        int w = icon_bitmap.getWidth();
        int h = icon_bitmap.getHeight();

        int i = 0, j = 0, n = 0;
        int[] pixels = new int[w * h];
        icon_bitmap.getPixels(pixels, 0, w, 0, 0, w, h);
        //0~1.0代表进度0%~100%
        int progressHeight = (int) (mHeight * mProgress);//相对应wave_path的P0为（x,mHeight * (1-0.55f)）
        for (; i < w; i++) {
            //当前像素相对贝塞尔曲线第一个点P0的横坐标
            int rX = (mWaveDx - dx) + (int) (((double) i / (double) w) * mWidth);
            //半周期个数
            int halfNum = rX / (mWaveDx / 2);
            int mod = rX % (mWaveDx / 2);
            double t = (double) mod / ((double) mWaveDx / 2);
            //numC用作常数,设置正负号
            int numC = (halfNum % 2) == 0 ? 1 : -1;
            //贝塞尔曲线的高度
            int bY = (int) (numC * t * (1 - t) * mWaveHeight * 2) + progressHeight;
            for (j = 0; j < h; j++) {
                int rY = (int) (((double) j / (double) h) * mHeight);
                //判断像素点是否在贝塞尔曲线高度之上
                if ((mHeight - rY) > bY) {
                    //透明
                    int gray=(int) (Color.red(pixels[j * w + i]) * 0.299 + Color.green(pixels[j * w + i]) * 0.587 + Color.blue(pixels[j * w + i]) * 0.114);
                    pixels[j * w + i] = Color.argb(255,gray,gray,gray);
                }
            }
        }
        //icon_bitmap_temp是用来制作一部分透明，一部分不透明这样的图，就是当前时刻要展示的前景图
        icon_bitmap_temp = Bitmap.createBitmap(pixels, 0, w, w, h, icon_bitmap.getConfig());
        canvas.drawBitmap(icon_bitmap_temp, icon_src_rect, icon_dst_rect, mPaint);
        mPaint.setColorFilter(null);

    }

    private void drawPath(Canvas canvas, float offset, int color) {

        wave_path.reset();
        //屏幕外
        wave_path.moveTo(-mWaveDx + dx, mHeight * (1-mProgress));

        for (int i = -mWaveDx; i < getWidth() + mWaveDx; i += mWaveDx) {
            //1/4 的距离做控制点 向下 2/4 的 结束
            wave_path.rQuadTo(mWaveDx / 4, -mWaveHeight, mWaveDx / 2, 0);
            wave_path.rQuadTo(mWaveDx / 4, mWaveHeight, mWaveDx / 2, 0);

        }
        wave_path.lineTo(mWidth, mHeight);
        wave_path.lineTo(0, mHeight);
        wave_path.close();

        wave_path_offset.reset();
        wave_path_offset.moveTo(-mWaveDx + dx + offset, mHeight * 0.45f);
        for (int i = -mWaveDx; i < getWidth() + mWaveDx; i += mWaveDx) {
            //1/4 的距离做控制点 向下 2/4 的 结束
            wave_path_offset.rQuadTo(mWaveDx / 4, -mWaveHeight, mWaveDx / 2, 0);
            wave_path_offset.rQuadTo(mWaveDx / 4, mWaveHeight, mWaveDx / 2, 0);

        }
        wave_path_offset.lineTo(mWidth, mHeight);
        wave_path_offset.lineTo(0, mHeight);
        wave_path_offset.close();

        mPaint.setXfermode(xfermode);
        mPaint.setColor(Color.parseColor("#FF9EFDFF"));
        //canvas.drawPath(wave_path_offset, mPaint);
        LinearGradient linearGradient = new LinearGradient(0, mHeight, 0, 0, new int[]{Color.parseColor("#FF008582"), Color.parseColor("#F400FBFF"), Color.parseColor("#CCFFFFFF")}, new float[]{0, 0.4f, 1f}, Shader.TileMode.MIRROR);
//        mPaint.setColor(Color.parseColor("#F400FBFF"));
        mPaint.setShader(linearGradient);
        canvas.drawPath(wave_path, mPaint);
        mPaint.setShader(null);
        mPaint.setXfermode(null);
    }

    public void drawStroke(Canvas canvas) {
        canvas.drawCircle(mWidth / 2, mWidth / 2, mWidth / 2 - dip2px(getContext(), 5), mPaint_offset);
    }


    public void waveAnimation() {
        ValueAnimator valueAnimator = ValueAnimator.ofInt(0, mWaveDx);
        // 设置属性动画时长
        valueAnimator.setDuration(2000);
        // 无线重复动画
        valueAnimator.setRepeatCount(ValueAnimator.INFINITE);
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                //水平方向的偏移量，值的区间为0~mWaveDx，根据偏移量重绘贝塞尔曲线
                dx = (int) animation.getAnimatedValue();
                invalidate();
            }
        });
        valueAnimator.start();
    }

    public void setProgress(int progress,int max) {
        mProgress=(float)progress/max;
    }
}
